
// Definition for a binary tree node.
function TreeNode(val, left, right) {
    this.val = (val===undefined ? 0 : val)
    this.left = (left===undefined ? null : left)
    this.right = (right===undefined ? null : right)
}

/**
 * @param {TreeNode} root1
 * @param {TreeNode} root2
 * @return {boolean}
 */
var leafSimilar = function(root1, root2) {
  let res1 = [], res2 = [];
  function preView1(node) {
    if(!node) return;
    preView1(node.left);
    preView1(node.right);
    if(!node.left && !node.right) {
      res1.push(node.val);
    }
  }
  preView1(root1);
  function preView2(node) {
    if(!node) return;
    preView2(node.left);
    preView2(node.right);
    if(!node.left && !node.right) {
      res2.push(node.val);
    }
  }
  preView2(root2);
  if(res1.length != res2.length) return false;

  for(let i = 0; i < res1.length; i++) {
    if(res1[i] != res2[i]) return false;
  }
  return true;
};
